<template>
  <div>
    <el-form
      style="margin-left: 20px"
      :inline="true"
      ref="form"
      :model="form"
      label-width="80px"
      :rules="rules"
    >
      <el-form-item label="班级" prop="gradeId">
        <el-select placeholder="请选择班级" v-model="form.gradeId" filterable>
          <el-option
            v-for="item in grades"
            :label="item.name"
            :value="item.id"
            :key="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="模块" prop="subjectId">
        <el-select
          @change="subjectChange"
          v-model="form.subjectId"
          placeholder="请选择模块"
        >
          <el-option
            v-for="item in subject"
            :label="item.name"
            :value="item.id"
            :key="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="章节" prop="chapter">
        <el-select multiple v-model="form.chapter" placeholder="请选择章节">
          <el-option
            v-for="item in chapter"
            :label="item.name"
            :value="item.name"
            :key="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="标题" prop="title">
        <el-input style="width: 300px" v-model="form.title" />
      </el-form-item>
      <el-form-item label="数量" prop="number">
        <el-input-number v-model="form.number"></el-input-number>
      </el-form-item>
      <el-form-item label="考试时间(分钟)" prop="time">
        <el-input-number v-model="form.time"></el-input-number>
      </el-form-item>
      <el-button type="primary" @click="submit('form')">提 交</el-button>
      <el-button type="primary" @click="reset('form')">重 置</el-button>
    </el-form>
  </div>
</template>

<script>
import zhiZhaoApi from "@/api/questionItem/questionItem";
import gradeApi from "@/api/grade/index";
import testResult from "@/views/test/testResult.vue";
import subjectApi from "@/api/subject/index";
import chapterApi from "@/api/chapter/index";
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style
export default {
  components: { testResult },
  data() {
    const validateNumber = (rule, value, callback) => {
      if (value < 1) {
        callback(new Error("出题数不得小于1！"));
      } else {
        callback();
      }
    };
    const validateTime = (rule, value, callback) => {
      if (value < 1) {
        callback(new Error("考试时间不得小于1！"));
      } else {
        callback();
      }
    };
    const validateQuestionItemId = (rule, value, callback) => {
      //校验规则是，试卷编号必须为纯数字，且首字符不能为0
      let pattern = /^[1-9]\d*$/;
      if (!pattern.test(value)) {
        callback(new Error("试卷编号必须是且首字符不能为0的纯数字！"));
      } else {
        callback();
      }
    };
    return {
      grades: [],
      form: {
        subjectId: "",
        number: 0,
        // questionItemId: "",
        time: "",
        chapter: "",
        gradeId: "",
        title: "",
      },
      subject: [],
      chapter: [],
      rules: {
        subjectId: [
          { required: true, message: "请选择模块！", trigger: "blur" },
        ],
        number: [
          { required: true, trigger: "blur", validator: validateNumber },
        ],
        // questionItemId: [
        //   {
        //     required: true,
        //     trigger: "blur",
        //     validator: validateQuestionItemId,
        //   },
        // ],
        title: [{ required: true, message: "请选择标题！", trigger: "blur" }],
        gradeId: [
          {
            required: true,
            trigger: "blur",
            message: "请选择班级！",
          },
        ],
        time: [{ required: true, trigger: "blur", validator: validateTime }],
        chapter: [{ required: false }],
      },
      tableData: [],
    };
  },
  watch: {
    "form.gradeId": {
      handler(newValue, oldValue) {
        this.setTitle();
      },
      deep: true,
    },
    "form.subjectId": {
      handler(newValue, oldValue) {
        this.setTitle();
      },
      deep: true,
    },
  },
  methods: {
    setTitle: async function () {
      if (this.form.subjectId && this.form.gradeId) {
        const res = await zhiZhaoApi.getCount(
          this.form.subjectId,
          this.form.gradeId
        );
        let subject = this.selectedSubjectLabel.substring(2, 4);
        let number = res.data + 1;
        let title =
          this.selectedGradeLabel + subject + "第" + number + "次考试";
        this.form.title = title;
      }
    },
    subjectChange(data) {
      this.form.chapter = "";
      chapterApi.getBySubjectId(data).then((res) => {
        this.chapter = res.data;
      });
    },
    submit(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          //todo 这里向服务器提交请求，出题，然后发给学员们做
          NProgress.start();
          zhiZhaoApi.batchInsert(this.form).then((res) => {
            this.$message({
              message: `${res.message}`,
              type: "success",
            });
            this.$router.push({
              path: `/testResult/index`,
              query: { title: this.form.title },
            });
          });
        } else {
          console.log("error submit!!");
          NProgress.done();
        }
      });
    },
    reset(form) {
      this.$refs[form].resetFields();
    },
    getSubject() {
      subjectApi.getAll().then((res) => {
        this.subject = res.data;
      });
    },
    getGrade() {
      gradeApi.allR3().then((res) => {
        this.grades = res.data;
      });
    },
  },
  created() {
    this.getSubject();
    this.getGrade();
  },
  computed: {
    selectedGradeLabel() {
      const selectedGrade = this.grades.find(
        (item) => item.id === this.form.gradeId
      );
      return selectedGrade ? selectedGrade.name : "";
    },
    selectedSubjectLabel() {
      const selectedSubject = this.subject.find(
        (item) => item.id === this.form.subjectId
      );
      return selectedSubject ? selectedSubject.name : "";
    },
  },
};
</script>

<style scoped></style>
